package service;

import dao.UserDao;
import domain.User;
import exception.LoginException;
import exception.RegisterException;
import utils.MailUtils;
import utils.ResponseCode;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import java.sql.SQLException;

public class UserServlet {
    private UserDao userDao=new UserDao();

    public void activeUser(String activeCode) throws  SQLException{
        userDao.activeUser(activeCode);
    }

    public  void  register(User user) throws RegisterException{
        User userDB=null;
        try {
             userDB = userDao.findUserByUsername(user.getUsername());
        }catch (SQLException e){
            throw  new RegisterException(ResponseCode.ERROR_DB);
        }
        if (userDB==null){//现在数据库中没有用户名，可以注册
          //添加一条记录
            try {
                userDao.addUser(user);
                //发送一封邮件
                String msg= "感谢您注册网上书城，点击<a href='http://localhost:8080/api/activeUser?activeCode="+ user.getActiveCode() + "'>&nbsp;激活&nbsp;</a>后使用。<br />为保障您的账户安全，请在24小时内完成激活操作";
                MailUtils.sendMail(user.getEmail(),msg);
            }catch (SQLException e) {
                throw new RegisterException(ResponseCode.ERROR_DB);
            }catch (AddressException e){
                //删除已经插入记录
                try {
                    userDao.delUser(user.getActiveCode());
                }catch (SQLException ee){
                    throw new RegisterException(ResponseCode.ERROR_DB);
                }
                throw new RegisterException(ResponseCode.ERROR_EMAIL_ADDRESS);
            }catch (MessagingException e){
                //删除已经插入记录
                try {
                    userDao.delUser(user.getActiveCode());
                }catch (SQLException ee){
                    throw new RegisterException(ResponseCode.ERROR_DB);
                }
                throw new RegisterException(ResponseCode.ERROR_EMAIL_SEND);
            }
        }else {//存在相同用户名，请更换用户名
            throw  new RegisterException(ResponseCode.ERROR_USERNAME);
        }
    }

    public void login(User user) throws LoginException {
        try {
            User userDB = userDao.findUserByUsernameAndPassword(user.getUsername(), user.getPassword());
            if (userDB == null) {//没有该用户或者密码不对
                 throw  new LoginException(ResponseCode.NOT_USER_OR_PASSWORD);
            } else {//找到了这个用户，密码也正确
                if (userDB.getState()==1) {

                }else {
                    throw new LoginException(ResponseCode.NOT_ACTIVE);
                }
            }
        } catch (SQLException | LoginException e) {
            e.printStackTrace();
            throw new LoginException(ResponseCode.ERROR_DB);
        }
    }
}